﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using DMS.NAVWebService;
using FileHelpers;


namespace GATCreditAppExportAndUpdateNav
{
    /// <summary>
    /// Export PDF document from existing Document Store in http://sharepoint/finance
    /// Run Powershell Script from DMS release to Import to New intranet site http://intranet.turners.co.nz
    /// Update NAV
    /// </summary>
    class Program
    {
        private static string _gat = "GAT";
        private static string _ca = "Credit Application";
        private static bool _isProd;
        private static string _preprodGATUrl;
        private static string _prodGATUrl;
        private static string _preprodCAUrl;
        private static string _prodCAUrl;
        private static string _filePath;
        private static string _destinationPath;
        static void Main(string[] args)
        {
            _filePath = ConfigurationManager.AppSettings["FilePath"];
            _destinationPath = ConfigurationManager.AppSettings["DestinationFolder"];
            string environment = ConfigurationManager.AppSettings["UpdateEnvironment"];
            if (environment.ToUpper().Equals("PREPROD"))
            {
                _isProd = false;
                _preprodCAUrl = ConfigurationManager.AppSettings["PreProdCAUrl"];
                _preprodGATUrl = ConfigurationManager.AppSettings["PreProdGATUrl"];

                if(!_preprodCAUrl.EndsWith("/"))
                    _preprodCAUrl += "/";
                if(!_preprodGATUrl.EndsWith("/"))
                    _preprodGATUrl += "/";
            }else
            {
                _isProd = true;
                _prodCAUrl = ConfigurationManager.AppSettings["ProdCAUrl"];
                _prodGATUrl = ConfigurationManager.AppSettings["ProdGATUrl"];

                if (!_prodCAUrl.EndsWith("/"))
                    _prodCAUrl += "/";
                if (!_prodGATUrl.EndsWith("/"))
                    _prodGATUrl += "/";
            }
            //ExportPDFfromDocumentStore();
            main_UpdateNAV();
            Console.ReadLine();
        }

        private static void main_UpdateNAV()
        {

            List<DocumentStore> ds = UpdateNAV();
            if (ds.Count > 0)
            {
                Console.WriteLine("ERRRORS ON UPDATING NAV.");
                System.IO.StreamWriter file = new System.IO.StreamWriter("E:\\Errors\\test.txt");
                foreach (DocumentStore documentStore in ds)
                {
                    file.WriteLine(String.Format("Customer No: {0}, File Url: {1}", documentStore.CustomerNo, documentStore.Url));
                    Console.WriteLine(String.Format("Customer No: {0}, File Url: {1}", documentStore.CustomerNo, documentStore.Url));
                }
                file.Close();
            }
        }

        private static List<DocumentStore> UpdateNAV()
        {
            List<DocumentStore> Errors = new List<DocumentStore>();
            DocumentStore[] records = LoadDatafromCsv();
            foreach (DocumentStore item in  records)
            {
                //continue process the item only if its either GAT or Credit Application
                if (item.DocType.Equals(_gat) || item.DocType.Equals(_ca))
                {

                    if (item.Url.EndsWith(","))
                        item.Url = item.Url.Substring(0, item.Url.Length - 1);
                    try
                    {
                        string url = item.Url;

                        string customerNumber = item.CustomerNo;
                        if(Regex.IsMatch(customerNumber,@"^\d+$"))
                        {
                            if(url.StartsWith("http://"))
                            {   
                                string fileName = GetFileName(url);
                                if(_isProd)
                                {
                                    if(item.DocType.Equals(_gat))
                                    {
                                        string itemUrl = _prodGATUrl + fileName;
                                        if(!UpdateNAVWS(item.DocType, item.CustomerNo, itemUrl))
                                        {
                                            Errors.Add(item);
                                        }
                                    }
                                    if(item.DocType.Equals(_ca))
                                    {
                                        string itemUrl = _prodCAUrl + fileName;
                                        if(!UpdateNAVWS(item.DocType, item.CustomerNo, itemUrl))
                                        {
                                            Errors.Add(item);
                                        }
                                    }
                                }
                                if(!_isProd)
                                {
                                    if(item.DocType.Equals(_gat))
                                    {
                                        string itemUrl = _preprodGATUrl + fileName;
                                        if(!UpdateNAVWS(item.DocType, item.CustomerNo, itemUrl))
                                        {
                                            Errors.Add(item);
                                        }
                                    }
                                    if(item.DocType.Equals(_ca))
                                    {
                                        string itemUrl = _preprodCAUrl + fileName;
                                        if(!UpdateNAVWS(item.DocType, item.CustomerNo, itemUrl))
                                        {
                                            Errors.Add(item);
                                        }
                                    }
                                }
                                Console.WriteLine("Item is updated: " + item.CustomerNo);
                                
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Errors.Add(item);
                    }
                }
            }
            return Errors;
        }

        private static bool UpdateNAVWS(string docType, string customerNo, string url)
        {
            SharepointImport ws = new SharepointImport();

            string username = ConfigurationManager.AppSettings["NAVWSUsername"];
            string password = ConfigurationManager.AppSettings["NAVWSPassword"];
            string domain = ConfigurationManager.AppSettings["NAVWSDomain"];
            string wsUrl = ConfigurationManager.AppSettings["NAVWSUrl"];

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(wsUrl))
                return false;

            ws.Credentials = new NetworkCredential(username,password,domain);

            string type = docType.Equals("GAT", StringComparison.CurrentCultureIgnoreCase) ? "GAT" : "CREDAPP";
            ws.Url = wsUrl;
            bool success = ws.LoadAccountURLs(type, customerNo, url);
            return success;
        }

        private static void ExportPDFfromDocumentStore()
        {
            List<DocumentStore> Errors = new List<DocumentStore>();
            DocumentStore[] records = LoadDatafromCsv();

            List<ExportDocs> GatsDocs = new List<ExportDocs>();
            List<ExportDocs> CaDocs = new List<ExportDocs>();

            foreach (DocumentStore item in records)
            {
                //continue process the item only if its either GAT or Credit Application
                if(item.DocType.Equals(_gat, StringComparison.CurrentCultureIgnoreCase) || item.DocType.Equals(_ca, StringComparison.CurrentCultureIgnoreCase))
                {

                    if (item.Url.EndsWith(","))
                        item.Url = item.Url.Substring(0, item.Url.Length - 1);

                    if (item.DocType.Equals(_gat, StringComparison.CurrentCultureIgnoreCase))
                    {
                        ExportDocs doc = new ExportDocs() {Type = ExportDocType.GAT, CustomerNumber = item.CustomerNo};
                        doc.DocumentDate = item.GetDocumentDate();

                        bool replaceGat = false;
                        bool existGat = false;
                        foreach (ExportDocs docs in GatsDocs)
                        {
                            if(docs.CustomerNumber.Equals(doc.CustomerNumber, StringComparison.CurrentCultureIgnoreCase) && docs.Type == doc.Type)
                            {
                                //replace the original one 
                                existGat = true;
                                if(doc.DocumentDate > docs.DocumentDate)
                                {
                                    replaceGat = true;
                                    break;
                                }else
                                {

                                    break;
                                }
                            }
                        }
                        if(!existGat)
                        {
                            GatsDocs.Add(doc);
                            replaceGat = true;
                        }

                        if(replaceGat)
                        {
                            try
                            {
                                string url = item.Url;
                                //download the PDF from the URL
                                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                                request.Credentials = new NetworkCredential("swu", "Password5", "Auctions");
                                Stream input = request.GetResponse().GetResponseStream();
                                string fileName = GetFileName(url);
                                if (!_destinationPath.EndsWith("\\"))
                                    _destinationPath += "\\";
                                string filePath = _destinationPath +"GAT\\" + fileName;
                                using (Stream file = File.Create(filePath))
                                {
                                    SaveStream(input, file);
                                }
                                Console.WriteLine(fileName);
                            }
                            catch (Exception e)
                            {
                                Errors.Add(item);
                            }
                        }
                    }

                    if (item.DocType.Equals(_ca, StringComparison.CurrentCultureIgnoreCase))
                    {
                        ExportDocs doc = new ExportDocs() { Type = ExportDocType.CA, CustomerNumber = item.CustomerNo };
                        doc.DocumentDate = item.GetDocumentDate();

                        bool replaceCa = false;
                        bool existCa = false;
                        foreach (ExportDocs docs in CaDocs)
                        {
                            if (docs.CustomerNumber.Equals(doc.CustomerNumber, StringComparison.CurrentCultureIgnoreCase) && docs.Type == doc.Type)
                            {
                                existCa = true;
                                //replace the original one 
                                if (doc.DocumentDate > docs.DocumentDate)
                                {
                                    replaceCa = true;
                                    break;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        if(!existCa)
                        {
                            CaDocs.Add(doc);
                            replaceCa = true;
                        }

                        if(replaceCa)
                        {
                            try
                            {
                                string url = item.Url;
                                //download the PDF from the URL
                                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                                request.Credentials = new NetworkCredential("swu", "Password5", "Auctions");
                                Stream input = request.GetResponse().GetResponseStream();
                                string fileName = GetFileName(url);
                                if (!_destinationPath.EndsWith("\\"))
                                    _destinationPath += "\\";
                                string filePath = _destinationPath +"CA\\"+  fileName;
                                using (Stream file = File.Create(filePath))
                                {
                                    SaveStream(input, file);
                                }
                                Console.WriteLine(fileName);
                            }
                            catch (Exception e)
                            {
                                Errors.Add(item);
                            }
                        }
                    }



                }
            }
            if(Errors.Count > 0)
            {
                Console.WriteLine("Total Errors in processing: " + Errors.Count);
                foreach (DocumentStore error in Errors)
                {
                    Console.WriteLine(error.CustomerName + ", " + error.CustomerNo + ", " + error.DocType + ", " + error.Url);
                }
            }
            Console.WriteLine("Download completed!");
            Console.ReadLine();

        }

        private static string GetFileName(string url)
        {
            return url.Substring(url.LastIndexOf("/", System.StringComparison.Ordinal) + 1, url.Length - url.LastIndexOf("/", System.StringComparison.Ordinal) - 1);
        }

        private static void SaveStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[8 * 1024];
            int len;
            while((len = input.Read(buffer, 0 ,buffer.Length)) > 0)
            {
                output.Write(buffer,0,len);
            }
        }

        private static DocumentStore[] LoadDatafromCsv()
        {
            FileHelperEngine engine = new FileHelperEngine(typeof(DocumentStore));

            DocumentStore[] records = engine.ReadFile(_filePath) as DocumentStore[];

            return records;
        }
    }

    public enum ExportDocType
    {
        GAT,
        CA
    }

    public class ExportDocs
    {
        public ExportDocType Type { get; set; }
        public string CustomerNumber { get; set; }
        public DateTime DocumentDate { get; set; }

    }
}
